package blog.controller;

import blog.entity.BatchResult;
import blog.entity.QueryJson;
import blog.entity.ResultJson;
import blog.pojo.ChapterLabel;
import blog.service.ChapterLabelService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/chapterLabel")
public class ChapterLabelController {

    @Autowired
    private ChapterLabelService chapterLabelService;

    @RequestMapping("/edit")
    public ResultJson edit(@RequestBody QueryJson<ChapterLabel> queryJson) throws Exception {
        if (queryJson.getEntity() == null) {
            return ResultJson.ARGUMENT_NULL;
        }
        return ResultJson.isSuccess(chapterLabelService.edit(queryJson.getEntity()));
    }

    @RequestMapping("/del")
    public ResultJson del(@RequestBody QueryJson<ChapterLabel> queryJson) throws Exception {
        if (queryJson.getEntity() == null) {
            return ResultJson.ARGUMENT_NULL;
        }
        return ResultJson.isSuccess(chapterLabelService.del(queryJson.getEntity().getId()));
    }

    @RequestMapping("/batchDel")
    public ResultJson batchDel(@RequestBody QueryJson<ChapterLabel> queryJson) throws Exception {
        int succ = 0, fail = 0;
        if (queryJson.getIds() == null) {
            return ResultJson.ARGUMENT_NULL;
        }
        for (Integer id : queryJson.getIds()) {
            if (chapterLabelService.del(id)) {
                succ++;
            } else {
                fail++;
            }
        }
        String msg = null;
        if (fail > 0) {
            msg = "部分正在使用中，无法删除";
        }
        return ResultJson.isSuccess(BatchResult.SET(succ, fail, msg));
    }

    @RequestMapping("/findPage")
    public ResultJson findPage(@RequestBody QueryJson<ChapterLabel> queryJson) throws Exception {
        if (queryJson.getPage() == null) {
            return ResultJson.ARGUMENT_NULL;
        }
        Page<ChapterLabel> page = chapterLabelService.getPage(queryJson.getPage(), queryJson.getKeywords());
        return ResultJson.isSuccess(page);
    }

    @RequestMapping("/findAll")
    public ResultJson findAll() throws Exception{
        return ResultJson.isSuccess(chapterLabelService.getAll());
    }
}
